import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';

import QueueAnim from 'rc-queue-anim'
import TweenOne from 'rc-tween-one'

import { connect } from 'dva';

import { Row, Col, Card, Form, Input, Select, Icon, Button, Dropdown, Menu, InputNumber, DatePicker, Modal, message, Badge, Divider, Steps, Radio, } from 'antd';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import StandardTable from '@/containers/StandardTable';
import StandardTableForm from '@/containers/StandardTable/StandardTableForm';
import StandardTableHandle from '@/containers/StandardTable/StandardTableHandle';
// import TableTab from '@/containers/TableTab';
import { feedbacks as tabList } from '@/commons/tabList';

import Integrals from './Integrals';
import Goods from './Goods';

import { users as columns } from '@/commons/columns';
import { users as map } from '@/commons/map';

import styles from './style.less';

const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
  .map(key => obj[key])
  .join(',');

const CreateModelIntegral = props => {
  const { queryRow, modalIntegralsVisible, form, handleUpdate, handleModalIntegralsVisible } = props;
  const okHandle = () => {
    console.log(123);
  };
  return (
    <Modal
      destroyOnClose
      width={1300}
      visible={modalIntegralsVisible}
      onOk={okHandle}
      onCancel={() => handleModalIntegralsVisible()}
      footer={null}
      bodyStyle={{padding: 0}}
    >
      <Integrals queryRow={queryRow} okHandle={okHandle} />
    </Modal>
  );
};

const CreateModelGoods = Form.create()(props => {
  const { queryRow, modalGoodsVisible, form, handleUpdate, handleModalGoodsVisible } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleUpdate(fieldsValue, 2);
    });
  };

  return (
    <Modal
      destroyOnClose
      width={1300}
      visible={modalGoodsVisible}
      onOk={okHandle}
      onCancel={() => handleModalGoodsVisible()}
      footer={null}
      bodyStyle={{padding: 0}}
    >
      <Goods queryRow={queryRow} okHandle={okHandle} />
    </Modal>
  );
});

/* eslint react/no-multi-comp:0 */
@connect(({ users, loading }) => ({
  users,
  loading: loading.models.users,
}))
@Form.create()
class TableList extends PureComponent {
  state = {
    modalIntegralsVisible: false,
    updateModalIntegralsVisible: false,
    modalGoodsVisible: false,
    updateModalGoodsVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    stepFormValues: {},
    queryRow: {},
  };

  columns = [
    ...columns, {
      title: '操作',
      width: 99,
      align: 'center',
      fixed: 'right',
      render: queryRow => (
        <Fragment>
          <Button 
            type="primary"
            icon="eye" 
            size="small" 
            onClick={this.handleModalIntegralsVisible.bind(null, queryRow)}
          >
            看幸运草详情
          </Button>
          <Button 
            type="primary"
            icon="eye" 
            size="small" 
            style={{marginTop: 8, width: '100%'}} 
            onClick={this.handleModalGoodsVisible.bind(null, queryRow)}
          >
            查看抽奖详情
          </Button>
        </Fragment>
      ),
    }
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'users/fetch',
    });
  }

  handleTabChange = type => {
    const { form, dispatch } = this.props;
    form.resetFields();

    dispatch({
      type: 'users/fetch',
      payload: { type }
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      from: pagination.current,
      size: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'users/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'users/fetch',
      payload: {},
    });
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;
    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'users/remove',
          payload: { id: selectedRows.map(row => row.id) },
          callback: ({ errno, data }) => {
            if (!errno && data) {
              dispatch({
                type: 'users/fetch'
              });
              this.setState({
                selectedRows: []
              });
              message.success(`删除成功 ${data} 条`);
            } else {
              message.error('删除失败！');
            }
          },
        });
        break;
      case 'update':
        dispatch({
          type: 'users/update',
          payload: { id: selectedRows.map(row => row.id) },
          callback: ({ errno, data }) => {
            if (errno) {
              message.error('更新失败！');
            } else {
              dispatch({
                type: 'users/fetch'
              });
              this.setState({
                selectedRows: []
              });
              message.success('更新成功！');
            }
          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState(state => ({
      ...state,
      selectedRows: rows
    }));
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        createdAt: fieldsValue.createdAt && fieldsValue.createdAt.valueOf(),
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'users/fetch',
        payload: values,
      });
    });
  };

  handleModalIntegralsVisible = (queryRow = {}) => {
    const payload = {}
    if (isNaN(queryRow.id)) {
      Object.assign(payload, {
        modalIntegralsVisible: false
      });
    } else {
      Object.assign(payload, {
        modalIntegralsVisible: true,
        queryRow
      });
    }
    this.setState(state => ({
      ...state,
      ...payload
    }));
  };

  handleModalGoodsVisible = (queryRow = {}) => {
    const payload = {}
    if (isNaN(queryRow.id)) {
      Object.assign(payload, {
        modalGoodsVisible: false
      });
    } else {
      Object.assign(payload, {
        modalGoodsVisible: true,
        queryRow
      });
    }
    this.setState(state => ({
      ...state,
      ...payload
    }));
  };

  handleUpdate = ({ remark }) => {
    const { dispatch } = this.props;
    const { id } = this.state;

    dispatch({
      type: 'users/update',
      payload: { id, remark },
      callback: ({ errno, data }) => {
        if (errno) {
          message.error('更新失败！');
        } else {
          dispatch({
            type: 'users/fetch'
          });
          message.success('更新成功！');
        }
      }
    });

    this.handleModalIntegralsVisible();
  };

  handleToggleTable = e => {
    e.preventDefault();

    const { form, dispatch } = this.props;
    form.resetFields();

    dispatch({
      type: 'users/fetch',
      payload: { type: e.target.value }
    });
  }

  handleActionClick = e => {
    e.preventDefault();

    message.error('EXCEL文档确认中')
  }

  render() {
    const {
      users: { data, status, type },
      loading,
      form,
    } = this.props;
    const { expandForm, queryRow, selectedRows, modalIntegralsVisible, updateModalIntegralsVisible, modalGoodsVisible, updateModalGoodsVisible, stepFormValues } = this.state;

    const parentIntegralMethods = {
      queryRow,
      modalIntegralsVisible,
      handleUpdate: this.handleUpdate,
      handleModalIntegralsVisible: this.handleModalIntegralsVisible,
    };

    const parentGoodsMethods = {
      queryRow,
      modalGoodsVisible,
      handleUpdate: this.handleUpdate,
      handleModalGoodsVisible: this.handleModalGoodsVisible,
    };

    const { pagination: { total } } = data;
    return (
      <PageHeaderWrapper 
        title="用户列表" 
        action={moment().format('LLLL')}
        tabList={tabList}
        tabActiveKey={String(type)}
        onTabChange={this.handleTabChange}
      >
        <Card bordered={false}>
          <StandardTableForm
            expandForm={expandForm}
            data={map}
            form={form}
            onSubmit={this.handleSearch}
            onReset={this.handleFormReset}
            onToggle={this.toggleForm}
          />
          <StandardTableHandle
            status={status}
            selectedRows={selectedRows}
            menuItems={{'remove': '删除', 'update': '拉黑'}}
            action={<Button type="primary" icon="download" onClick={this.handleActionClick}>EXCEL</Button>}
            onToggleTable={this.handleToggleTable}
            onMenuClick={this.handleMenuClick}
          />
          <StandardTable
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            bordered={true}
            size="small"
            scroll={{ x: 1300 }}
            columns={this.columns}
            expandedRowRender={record => <p style={{ marginBottom: 0 }}>备注：{record.remark}</p>}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Card>
        <CreateModelIntegral {...parentIntegralMethods} />
        <CreateModelGoods {...parentGoodsMethods} />
      </PageHeaderWrapper>
    );
  }
}

export default TableList;